package com.alferd.mall.mq.api;

import com.alfred.mall.mq.api.SeckillMqSendService;
import com.alfred.mall.mq.api.dto.MiaoshaMessageDTO;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.AbstractJavaTypeMapper;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;

@Service
@Slf4j
public class SendSeckillMesageServiceApi implements SeckillMqSendService {

    @Autowired
    private Environment env;

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Override
    public void sendSeckillMessage(MiaoshaMessageDTO miaoshaMessageDTO) {
        try {
            log.info("抢到秒杀商品了，开始发送消息 {}", miaoshaMessageDTO);
            rabbitTemplate.setMessageConverter(new Jackson2JsonMessageConverter());
            rabbitTemplate.setExchange(env.getProperty("user.miaosha.exchange.name"));
            rabbitTemplate.setRoutingKey(env.getProperty("user.miaosha.routing.key.name"));
//            Message message = MessageBuilder.withBody(objectMapper.writeValueAsBytes(miaoshaMessageDTO)).
//                    setDeliveryMode(MessageDeliveryMode.PERSISTENT).build();
//            rabbitTemplate.convertAndSend(message);
            rabbitTemplate.convertAndSend(miaoshaMessageDTO, new MessagePostProcessor() {
                @Override
                public Message postProcessMessage(Message message) throws AmqpException {
                    MessageProperties messageProperties = message.getMessageProperties();
                    messageProperties.setHeader(AbstractJavaTypeMapper.DEFAULT_CONTENT_CLASSID_FIELD_NAME, MiaoshaMessageDTO.class);
                    return message;
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
            log.error("抢单消息入队失败", e);
        }
    }
}
